import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/models/chat_message/xindong_custom_message.dart';
import 'package:xindong/models/chat_message/xindong_signal_message.dart';
import 'package:xindong/utils/xindong_text_util.dart';

class XinDongConversionUtil {
  // 格式转换数量
  //
  // count 值
  // decimal 小数位数
  static String formatCount(int? count, {int decimal = 1}) {
    if (count == null) {
      return "0";
    }
    if (count < 1000) {
      return count.toString();
    } else if (count < 100000) {
      return '${(count / 1000.0).toStringAsFixed(decimal)}K';
    } else if (count < 10000000) {
      return '${(count / 1000000.0).toStringAsFixed(decimal)}M';
    }
    return '10M+';
  }

  // 格式转换金额
  static String formatMoney(double? money) {
    if (money == null) {
      return "0.00";
    }
    return money.toStringAsFixed(2);
  }

  // 格式转换手机号（185****8888）
  static String formatPhone(String? phone, {String pattern = '****'}) {
    String showContent = phone ?? "";
    if (showContent.length >= 7) {
      showContent = showContent.replaceFirst(RegExp(r'(?<=\d{3})(\d{4})'), pattern);
    }
    return showContent;
  }

  // 格式转换账户名（185****8888）
  //
  // account 账户
  static String formatAccount(String? account) {
    String showContent = account ?? "";
    if (showContent.length >= 7) {
      showContent = showContent.replaceRange(3, showContent.length - 4, '*' * 4);
    }
    return showContent;
  }

  // 格式化URL，自动补偿或去除多余的/等，让地址变标准
  //
  // baseUrl 基url
  // path 路径
  static String formatUrl(String baseUrl, String path) {
    var url = path;
    if (!url.startsWith(RegExp(r'https?:'))) {
      url = baseUrl + url;
      var s = url.split(':/');
      url = '${s[0]}:/${s[1].replaceAll('//', '/')}';
    }
    return url;
  }

  // 是否有新版本
  static bool hasNewVersion(String version, String latestVersion) {
    Version v1 = Version.parse(version);
    Version v2 = Version.parse(latestVersion);
    return v1.compareTo(v2) < 0;
  }

  // 单词截断
  static String xindong_breakWord(String? word) {
    if (TextUtil.isEmpty(word)) {
      return "";
    }
    String breakWord = "";
    word!.runes.forEach((element) {
      breakWord += String.fromCharCode(element);
      breakWord += '\u200B';
    });
    return breakWord;
  }

  /// 获取视图相对屏幕坐标
  ///
  /// offsetY 可设置偏远量Y
  static Offset xindong_getWidgetOffset(BuildContext context, {double offsetY = 0}) {
    final RenderObject? renderObject = context.findRenderObject();
    var vector3 = renderObject?.getTransformTo(null).getTranslation();
    if (vector3 == null) {
      return Offset.zero;
    }
    return Offset(vector3.x, vector3.y + offsetY);
  }

  /// 获取视图的大小
  static Size xindong_getWidgetSize(BuildContext context) {
    final RenderObject? renderObject = context.findRenderObject();
    if (renderObject == null) {
      return Size.zero;
    }
    return renderObject.semanticBounds.size;
  }

  // 转换Map解码Unicode Json字符串
  //
  // unicode 编码后的Json字符串
  // return Map
  static Map<String, dynamic> decodeUnicodeJsonToMap(String unicode) {
    String jsonString = Uri.decodeQueryComponent(unicode, encoding: utf8);
    Map<String, dynamic> result = json.decode(jsonString);
    return result;
  }

  // Map 转义字符串
  static String mapToDecodeJson(Map dataMap) {
    try {
      // 模型转Json字符串
      String jsonString = json.encode(dataMap);
      // 转义字符
      return Uri.encodeQueryComponent(jsonString, encoding: utf8);
    } catch (e) {
      return "";
    }
  }

  // 模型转Map，支持模型嵌套(得保证模型内部没错误，如late要有值Converting object to an encodable object failed: Instance of)
  static Map<String, dynamic> modelToMap(var model) {
    if (model == null) return {};
    String jsonString = json.encode(model);
    return jsonDecode(jsonString);
  }

  // 模型转换成Json转义字符(得保证模型内部没错误，如late要有值Converting object to an encodable object failed: Instance of)
  static String? modelToDecodeJson(var model) {
    try {
      // 模型转Json字符串
      String jsonString = json.encode(model.toJson());
      return jsonString;
      // 转义字符
      // return Uri.encodeQueryComponent(jsonString, encoding: utf8);
    } catch (e) {
      return null;
    }
  }

  // 转义字符 转换成消息模型
  static XinDongCustomMessage? decodeJsonToMessageClass(String text) {
    try {
    // 转义字符 -> Json字符串
    // String jsonString = Uri.decodeQueryComponent(text, encoding: utf8);
    // Json字符串 -> Map集合
    Map<String, dynamic> dataMap = json.decode(text);
    // Map -> 模型
    return XinDongCustomMessage.fromJson(dataMap);
    } catch (e) {
      mCatchPrint(e);
      return null;
    }
  }

  // 转义字符 转换成信令模型
  static XinDongSignalMessage decodeJsonToSignalClass(String decodeString) {
    try {
      // 转义字符 -> Json字符串
      // String jsonString = Uri.decodeQueryComponent(decodeString, encoding: utf8);
      // Json字符串 -> Map集合
      Map<String, dynamic> dataMap = json.decode(decodeString);
      // Map -> 模型
      return XinDongSignalMessage.fromJson(dataMap);
    } catch (e) {
      return XinDongSignalMessage();
    }
  }
}
